package com.jweb.util;

import java.util.Arrays;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jweb.core.handle.Handle;

/**
 * 发送邮件工具类
 * 
 * @author yuanqiyong
 */
public class MailUtil {

	private String fromMail = "";
	private String fromPass = "";
	private String hostName = "";
	private Logger log = LoggerFactory.getLogger(Handle.class);

	public MailUtil(String fromMail, String fromPass, String hostName) {
		this.fromMail = fromMail;
		this.fromPass = fromPass;
		this.hostName = hostName;
	}

	/**
	 * 发送邮件
	 * 
	 * @param emails对方邮箱
	 * @param title标题F
	 * @param content内容
	 * @param nickName发件人别名
	 */
	public boolean sendMail(String[] emails, String title, String content, String nickName) {
		boolean bo = false;
		try {
			// 建立邮件会话
			Properties props = new Properties();
			// 存储发送邮件服务器的信息
			props.put("mail.smtp.host", "smtp." + hostName + ".com");
			// 同时通过验证
			props.put("mail.smtp.auth", "true");
			// 根据属性新建一个邮件会话
			Session mailSession = Session.getInstance(props);
			// 由邮件会话新建一个消息对象
			MimeMessage message = new MimeMessage(mailSession);
			// 设置邮件
			InternetAddress from = new InternetAddress(javax.mail.internet.MimeUtility.encodeText(nickName) + "<" + fromMail + ">");
			// 设置发件人的地址
			message.setFrom(from);
			// 设置收件人,并设置其接收类型为TO
			InternetAddress[] sendTo = new InternetAddress[emails.length];
			for (int i = 0; i < emails.length; i++) {
				sendTo[i] = new InternetAddress(emails[i]);
			}
			message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);
			// 设置标题
			message.setSubject(title);
			// 设置信件内容
			Multipart mp = new MimeMultipart();
			BodyPart html = new MimeBodyPart();
			// 设置内容
			html.setContent(content, "text/html; charset=utf-8");// html内容
			// html.setText(content);//文本内容
			mp.addBodyPart(html);
			// 设置附件
			message.setContent(mp, "text/html; charset=utf-8");
			// 设置发信时间
			message.setSentDate(new Date());
			// 存储邮件信息
			message.saveChanges();
			// 发送邮件
			Transport transport = mailSession.getTransport("smtp");
			// 以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址,第二个参数为用户名,第三个参数为密码
			transport.connect("smtp." + hostName + ".com", fromMail, fromPass);
			// 发送邮件,其中第二个参数是所有已设好的收件人地址
			log.info("[发送邮件]to={};title={}", new Object[] { Arrays.toString(emails), title });
			transport.sendMessage(message, message.getAllRecipients());
			bo = true;
		} catch (Exception e) {
			bo = false;
			e.printStackTrace();
		}
		log.info("[发送邮件-{}]", bo ? "成功" : "失败");
		return bo;
	}
}